﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace BluePortal.Framework
{
    [DataContract]
    public class FindParameters
    {
        [DataMember]
        public int? Start;

        [DataMember]
        public int? Count;

        [DataMember]
        public string OrderBy;

        [DataMember]
        public string OrderByDescending;

        [DataMember]
        public bool GetTotalCount = false;
    }

    public class FindResultHelper 
    {
        public static FindResult<T> ToFindResult<T>(IQueryable<T> query, FindParameters param)
        {
            FindResult<T> res = new FindResult<T>();
            if ((param != null) && (param.GetTotalCount == true))
            {                
                res.TotalCount = query.Count();
            }
            if ((param != null) && (param.Start.HasValue))
            {
                query = query.Skip<T>(param.Start.Value);
            }
            if ((param != null) && (param.Count.HasValue))
            {
                query = query.Take<T>(param.Count.Value);
            }
            if ((param != null) && (!string.IsNullOrEmpty(param.OrderBy)))
            {
                query = (IQueryable<T>)query.OrderBy(param.OrderBy);
            }
            if ((param != null) && (!string.IsNullOrEmpty(param.OrderByDescending)))
            {
                query = (IQueryable<T>)query.OrderBy(param.OrderByDescending + " DESC");
            }

            res.Enumerable = from e in query.AsEnumerable() select e; //.ToList();           

            return res;
        }
    }
}
